<template>
  <Layout>
    <div class="fade-in">
      <div class="flex justify-between items-center mb-6">
        <div>
          <h2 class="text-2xl font-bold text-gray-800">商品管理</h2>
          <p class="text-gray-600 mt-1">管理所有可供销售的商品</p>
        </div>
        <button
          @click="showAddProductModal = true"
          class="btn-primary px-6 py-2 rounded-lg text-white flex items-center"
        >
          <i class="fas fa-plus mr-2"></i>
          添加商品
        </button>
      </div>

      <!-- 搜索和筛选 -->
      <div class="bg-white rounded-xl shadow-sm overflow-hidden table-container mb-6">
        <div class="p-4 table-header">
          <div class="flex items-center justify-between">
            <div class="flex items-center space-x-4">
              <div class="relative">
                <input
                  v-model="searchQuery"
                  type="text"
                  placeholder="搜索商品..."
                  class="pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:border-indigo-500"
                />
                <i class="fas fa-search absolute left-3 top-3 text-gray-400"></i>
              </div>
              <!-- TODO: 添加商品分类筛选 -->
              <select
                v-model="categoryFilter"
                class="border rounded-lg px-4 py-2 focus:outline-none focus:border-indigo-500"
              >
                 <option value="">所有分类</option>
                 <!-- TODO: 从后端获取分类列表 -->
                 <option value="food">食品</option>
                 <option value="toy">玩具</option>
                 <option value="accessory">配件</option>
                 <option value="other">其他</option>
              </select>
            </div>
          </div>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="bg-white rounded-xl shadow-sm overflow-hidden table-container">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">名称</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">分类</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">价格</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">库存</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="product in filteredProducts" :key="product.id" class="hover:bg-gray-50">
              <td class="px-6 py-4 whitespace-nowrap">{{ product.id }}</td>
              <td class="px-6 py-4 whitespace-nowrap">{{ product.name }}</td>
              <td class="px-6 py-4 whitespace-nowrap">{{ getCategoryName(product.category) }}</td>
              <td class="px-6 py-4 whitespace-nowrap">¥{{ product.price.toFixed(2) }}</td>
              <td class="px-6 py-4 whitespace-nowrap">{{ product.stock }}</td>
              <td class="px-6 py-4 whitespace-nowrap space-x-2">
                <button
                  @click="addToCart(product)"
                  class="text-blue-600 hover:text-blue-900"
                  :disabled="product.stock <= 0"
                  :class="{'opacity-50 cursor-not-allowed': product.stock <= 0}"
                >
                  <i class="fas fa-cart-plus"></i>
                </button>
                <button
                  @click="editProduct(product)"
                  class="text-yellow-600 hover:text-yellow-900"
                >
                  <i class="fas fa-edit"></i>
                </button>
                <button
                  @click="deleteProduct(product.id)"
                  class="text-red-600 hover:text-red-900"
                >
                  <i class="fas fa-trash"></i>
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 添加/编辑商品模态框 -->
    <div
      v-if="showAddProductModal || showEditProductModal"
      class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full flex items-center justify-center"
    >
      <div class="relative p-6 w-full max-w-md bg-white rounded-xl shadow-lg">
        <h3 class="text-xl font-semibold text-gray-800 mb-4">
          {{ showEditProductModal ? '编辑商品' : '添加商品' }}
        </h3>
        <form @submit.prevent="handleSubmit" class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700">商品名称</label>
            <input
              v-model="productForm.name"
              type="text"
              required
              class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 p-2"
            />
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700">商品分类</label>
            <select
              v-model="productForm.category"
              required
              class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 p-2"
            >
               <option value="">请选择分类</option>
               <!-- TODO: 从后端获取分类列表 -->
               <option value="food">食品</option>
               <option value="toy">玩具</option>
               <option value="accessory">配件</option>
               <option value="other">其他</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700">价格</label>
            <input
              v-model.number="productForm.price"
              type="number"
              required
              step="0.01"
              class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 p-2"
            />
          </div>
           <div>
            <label class="block text-sm font-medium text-gray-700">库存</label>
            <input
              v-model.number="productForm.stock"
              type="number"
              required
              class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 p-2"
            />
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700">描述</label>
            <textarea
              v-model="productForm.description"
              rows="3"
              class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 p-2"
            ></textarea>
          </div>
          <div class="flex justify-end space-x-3 mt-5">
            <button
              type="button"
              @click="closeModal"
              class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300"
            >
              取消
            </button>
            <button
              type="submit"
              class="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700"
            >
              保存
            </button>
          </div>
        </form>
      </div>
    </div>
  </Layout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import Layout from '../components/Layout.vue'
import { productService, cartService } from '../services/api' // 确保导入商品服务和购物车服务

const products = ref([])
const searchQuery = ref('')
const categoryFilter = ref('')
const showAddProductModal = ref(false)
const showEditProductModal = ref(false)
const productForm = ref({
  id: null,
  name: '',
  category: '',
  price: null,
  stock: null,
  description: '',
})

// 过滤后的商品列表
const filteredProducts = computed(() => {
  // Ensure products.value is an array before filtering
  if (!Array.isArray(products.value)) {
    return [];
  }
  return products.value.filter(product => {
    const matchesSearch = product.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchesCategory = !categoryFilter.value || product.category === categoryFilter.value
    return matchesSearch && matchesCategory
  })
})

// 获取分类名称 (TODO: 需要根据后端返回的分类列表动态生成)
const getCategoryName = (category) => {
   const categories = {
     food: '食品',
     toy: '玩具',
     accessory: '配件',
     other: '其他'
   }
   return categories[category] || category
}

// 加载商品列表
const loadProducts = async () => {
  try {
    const response = await productService.getAll()
    // Check if response has a data property which is an array
    if (response && Array.isArray(response.data)) {
      products.value = response.data
    } else {
      console.error('productService.getAll() did not return expected format:', response);
      products.value = []; // Initialize as empty array on unexpected response
    }
  } catch (error) {
    console.error('Failed to load products:', error)
    products.value = []; // Initialize as empty array on error
  }
}

// 添加商品
const addProduct = async () => {
  try {
    const newProduct = await productService.create(productForm.value)
    products.value.unshift(newProduct)
    closeModal()
    alert('添加商品成功')
  } catch (error) {
    console.error('Failed to add product:', error)
    alert('添加商品失败')
  }
}

// 编辑商品
const editProduct = (product) => {
  productForm.value = { ...product }
  showEditProductModal.value = true
}

// 更新商品
const updateProduct = async () => {
  try {
    const updatedProduct = await productService.update(productForm.value.id, productForm.value)
    const index = products.value.findIndex(p => p.id === updatedProduct.id)
    if (index !== -1) {
      products.value[index] = updatedProduct
    }
    closeModal()
    alert('更新商品成功')
  } catch (error) {
    console.error('Failed to update product:', error)
    alert('更新商品失败')
  }
}

// 删除商品
const deleteProduct = async (id) => {
  if (!confirm('确定要删除这个商品吗？')) {
    return
  }

  try {
    await productService.delete(id)
    products.value = products.value.filter(p => p.id !== id)
    alert('删除商品成功')
  } catch (error) {
    console.error('Failed to delete product:', error)
    alert('删除商品失败')
  }
}

// 添加到购物车
const addToCart = async (product) => {
  try {
    // 检查库存
    if (product.stock <= 0) {
        alert('该商品库存不足');
        return;
    }
    // TODO: 商品和宠物添加到购物车的接口调用逻辑需要区分
    // 假设后端接口可以通过 product_id 或 pet_id 来区分
    const itemToAdd = {
        product_id: product.id, // 对于商品，发送 product_id
        quantity: 1 // 默认数量为 1
    };

    await cartService.addItem(itemToAdd);

    alert('成功添加到购物车');
    // 理论上添加成功后，购物车图标或提示应更新数量，但这里先只提示成功
  } catch (error) {
    console.error('Failed to add to cart:', error);
    alert(error.response?.data?.error || '添加到购物车失败');
  }
}

// 处理表单提交
const handleSubmit = () => {
  if (showEditProductModal.value) {
    updateProduct()
  } else {
    addProduct()
  }
}

// 关闭模态框
const closeModal = () => {
  showAddProductModal.value = false
  showEditProductModal.value = false
  productForm.value = {
    id: null,
    name: '',
    category: '',
    price: null,
    stock: null,
    description: '',
  }
}

onMounted(() => {
  loadProducts()
})
</script>

<style scoped>
.table-container {
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  border-radius: 10px;
  overflow: hidden;
}

.table-header {
  background: linear-gradient(135deg, #f8fafc 0%, #edf2f7 100%);
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  transition: all 0.3s;
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

/* 美化表格 */
table {
  border-collapse: collapse;
  width: 100%;
}

thead tr {
  border-bottom: 1px solid #e0e0e0;
}

th {
  background-color: #f5f5f5; /* 与主内容区背景色一致 */
  color: #616161; /* 深灰色文字 */
  text-align: left;
  padding: 12px 24px; /* 增加内边距 */
  font-weight: 600;
}

tbody tr {
  border-bottom: 1px solid #eeeeee;
}

tbody tr:last-child {
  border-bottom: none;
}

td {
  padding: 12px 24px; /* 增加内边距 */
  vertical-align: middle;
}

tbody tr.hover\:bg-gray-50:hover {
  background-color: #fafafa; /* 浅色悬停背景 */
}

/* 美化操作按钮 */
.whitespace-nowrap.space-x-2 button {
    transition: color 0.2s ease-in-out;
}

.whitespace-nowrap.space-x-2 button:hover {
    opacity: 0.8;
}

/* 美化模态框 */
.fixed.inset-0.bg-gray-600.bg-opacity-50.overflow-y-auto.h-full.w-full.flex.items-center.justify-center {
    background-color: rgba(0, 0, 0, 0.6); /* 更深的背景遮罩 */
}

.relative.p-6.w-full.max-w-md.bg-white.rounded-xl.shadow-lg {
    padding: 24px;
    background-color: #ffffff;
    border-radius: 12px;
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.relative.p-6.w-full.max-w-md.bg-white.rounded-xl.shadow-lg h3 {
    border-bottom: 1px solid #eeeeee;
    padding-bottom: 16px;
    margin-bottom: 16px;
}

.relative.p-6.w-full.max-w-md.bg-white.rounded-xl.shadow-lg input,
.relative.p-6.w-full.max-w-md.bg-white.rounded-xl.shadow-lg select,
.relative.p-6.w-full.max-w-md.bg-white.rounded-xl.shadow-lg textarea {
    border: 1px solid #e0e0e0;
    border-radius: 6px;
    padding: 8px 12px;
    font-size: 1rem;
}

.relative.p-6.w-full.max-w-md.bg-white.rounded-xl.shadow-lg input:focus,
.relative.p-6.w-full.max-w-md.bg-white.rounded-xl.shadow-lg select:focus,
.relative.p-6.w-full.max-w-md.bg-white.rounded-xl.shadow-lg textarea:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
    outline: none;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-10px); }
  to { opacity: 1; transform: translateY(0); }
}

.fade-in {
  animation: fadeIn 0.3s ease-out;
}

.table-container {
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  border-radius: 10px;
  overflow: hidden;
}

.table-header {
  background: linear-gradient(135deg, #f8fafc 0%, #edf2f7 100%);
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  transition: all 0.3s;
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}
</style> 